package com.mytomcat.servlet;


import com.util.log.Logger;

import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.sql.SQLOutput;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class MyHttpServletRequest {
    private static Logger log = Logger.getLogger(MyHttpServletRequest.class);

    private String url = "/404";

    private String servletPath = "/";

    private String method = "GET";

    // 请求的参数 如：/test/get?参数1=x&参数2=y&参数1=xx  数组表现为多个名字一样所以map的value是String[]
    Map<String, String[]> parameterMap = new HashMap<>();

    public MyHttpServletRequest(Socket socket) {
        /**
         * HTTP请求协议
         * GET /user/list HTTP/1.1
         * Connection: Keep-Alive
         */
        try {
            byte[] bytes = new byte[1024]; // socket的inputStream.read()没有内容会阻塞 所以就只读一次
            socket.getInputStream().read(bytes);
            String request = new String(bytes);
            log.trace("新连接: " + socket.getRemoteSocketAddress());
            log.trace("请求报文: " + request);

            String httpHead = request.split("\n")[0];
            url = httpHead.split("\\s")[1];
            int index = url.indexOf("?"); // 解析url带有参数 eg: /user/list?pageNum=1&pageSize=10
            if (index >= 0) {
                url = URLDecoder.decode(url, "UTF-8"); // url编码转换
                servletPath = url.substring(0, index);
                String paramsStr = url.substring(index + 1);
                String[] params = paramsStr.split("&");
                for (String param : params) { // eg: [pageNum=1, pageSize=10]
                    index = param.indexOf("=");
                    String paramName = param.substring(0, index);
                    String[] values;
                    if (!parameterMap.containsKey(paramName)) {
                        values = new String[]{param.substring(index + 1)};
                    } else {
                        values = parameterMap.get(paramName);
                        values = Arrays.copyOf(values, values.length + 1);
                        values[values.length - 1] = param.substring(index + 1);
                    }
                    parameterMap.put(paramName, values);
                }
            } else
                servletPath = url;
            method = httpHead.split("\\s")[0];
        } catch (Exception e) {
            log.trace("非HTTP请求");
        }
        log.trace(this.toString());
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public Map<String, String[]> getParameterMap() {
        return parameterMap;
    }

    public void setParameterMap(Map<String, String[]> parameterMap) {
        this.parameterMap = parameterMap;
    }


    public String getServletPath() {
        return servletPath;
    }

    public void setServletPath(String path) {
        this.servletPath = path;
    }

    @Override
    public String toString() {
        return "MyHttpServletRequest{" +
                "url='" + url + '\'' +
                ", servletPath='" + servletPath + '\'' +
                ", method='" + method + '\'' +
                ", parameterMap=" + parameterMap +
                '}';
    }
}
